/**
 * 系统平台
 * moonvip_admin
 * com.tz.web.shoporder
 * ShoporderController.java
 * 创建人:小胡
 * 时间：2016年12月20日 11:25:23
 *
 */
package com.tz.web.shoporder;

import com.tz.auth.AuthPassport;
import com.tz.bean.ReceiveTest;
import com.tz.bean.Service;
import com.tz.bean.Shoporder;
import com.tz.bean.TzParams;
import com.tz.service.receivetest.IReceiveTestService;
import com.tz.service.shoporder.IShoporderService;
import com.tz.util.KdniaoTrackQueryAPI;
import com.tz.util.TmFileUtil;
import com.tz.util.TmStringUtils;
import com.tz.util.qiniuUtils.QiniuParamter;
import com.tz.util.qiniuUtils.QiniuUtil;
import com.tz.util.weixinUtils.template.CommonOrder;
import com.tz.util.weixinUtils.template.WeixinMsgPushUtil;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tz.util.TzConstant.SESSION_USER_USERNAME;

/**
 * 商城订单管理web
 * ShoporderController
 * 创建人:小胡
 * 时间：2016年12月20日 11:25:23
 * @version 1.0.0
 *
 */
@Controller
@RequestMapping("/admin/order")
public class ShoporderController {

    @Resource
    private IShoporderService shoporderService;

    @Resource
    private IReceiveTestService receiveTestService;

    private final  static  String key_suff =   "shop/good";

    private static Logger logger = LoggerFactory.getLogger(ShoporderController.class);

    /*列表查询*/
    @AuthPassport
    @RequestMapping("/shoporder/list")
    public String list(TzParams params, Model model){
        model.addAttribute("params", params);
        return "order/shoporder/list";
    }

    /*模板页面*/
    @RequestMapping("/shoporder/template")
    public String template(TzParams params, Model model){
        List<Map<String ,Object>> allshopStatus  =  shoporderService.getAllShopStatus();
        model.addAttribute("allshopStatus" , allshopStatus);
        params.setType("006");
        //查询得到所有的
        model.addAttribute("datas", shoporderService.findShoporders(params));
        model.addAttribute("itemCount", shoporderService.count(params));
        return "order/shoporder/template";
    }


    @AuthPassport
    @RequestMapping("/shoporder/detail/{orderno}")
    public String detail(@PathVariable("orderno")  String orderno ,Model model){
        //根据订单号查询 商城订单的相关信息
        Map<String , Object>   order = shoporderService.findShopOrderByOrderno(orderno);
        //根据订单号查询商城订单的商品信息
        List<HashMap<String , Object>> gooddetails = shoporderService.getGoodDetailByOrdeno(orderno);
        model.addAttribute("order" , order);
        model.addAttribute("gooddetails" , gooddetails);
        return "order/shoporder/detail";
    }


    @AuthPassport
    @ResponseBody
    @RequestMapping(value="/shoporder/delete",method=RequestMethod.POST)
    public String delete(TzParams params){
        shoporderService.delete(params);
        return "success";
    }

    @ResponseBody
    @RequestMapping(value="/shoporder/update",method= RequestMethod.POST)
    public String update(Shoporder shoporder){
        shoporderService.update(shoporder);
        return "success";
    }

    @RequestMapping("/add")
    public String add(TzParams params){
        return "order/shoporder/add";
    }

    @AuthPassport
    @RequestMapping(value = "/shoporder/edit/{id}" ,method = RequestMethod.GET)
    public String edit(@PathVariable("id") Integer id , Model model){
        HashMap<String ,Object> shoporder = shoporderService.getShoporder(id);
        model.addAttribute("shoporder",shoporder);
        return "order/shoporder/edit";
    }


    @RequestMapping("/addReceiveTest/{orderno}/{type}/{openid}")
    public String addReceiveTest(@PathVariable("orderno")String orderno ,@PathVariable("type")String type ,@PathVariable("openid")String openid ,Model model){
        //根据订单号查询 商城订单的相关信息
        model.addAttribute("orderno" , orderno);
        model.addAttribute("type" , type);
        model.addAttribute("openid" , openid);
        return "order/addReceiveTest";
    }

    @RequestMapping("/saveReceiveTest")
    public String saveReceiveTest(ReceiveTest receiveTest , String type, String openid) throws IOException {
        String key_suff = "receiveTest";
        //本地文件路径
        String path = receiveTest.getImgurl().replace("\"","");
        //拼接上传的key
        String goodKey = key_suff  + "/"+path.substring(path.lastIndexOf("/")+1);
        //去七牛上传指定的文件并为其命名key
        QiniuUtil.upload(path , goodKey);
        //获得七牛图片外链
        String qiniuUrl = QiniuParamter.URL + goodKey;
        //删除本地文件
        TmFileUtil.delete(new File(path));
        //根据订单号查询 商城订单的相关信息
        receiveTest.setImgurl(qiniuUrl);
        receiveTestService.save(receiveTest);
        String returnUrl = "";
        if("001".equals(type)){
            shoporderService.update(new Shoporder(receiveTest.getOrderNo() , "001004"));
            returnUrl =  "redirect:refurbish/detail/";
        }
        if("002".equals(type)){
            shoporderService.update(new Shoporder(receiveTest.getOrderNo() , "002006"));
            returnUrl =  "redirect:repair/detail/";
        }
        if("003".equals(type)){
            shoporderService.update(new Shoporder(receiveTest.getOrderNo() , "003004"));
            //根据opendid查询用户名
            String nickname = shoporderService.getNickname(openid);
            returnUrl =  "redirect:testing/detail/";
        }
        if("004".equals(type)){
            shoporderService.update(new Shoporder(receiveTest.getOrderNo() , "004003"));
            returnUrl =  "redirect:recycle/detail/";
        }
        if("005".equals(type)){
            shoporderService.update(new Shoporder(receiveTest.getOrderNo() , "005003"));
            returnUrl =  "redirect:exchange/detail/";
        }
        
        logger.info("===上传收货证明完成，向用户推送门店收货T10模板消息开始=====");
        CommonOrder commonOrder = shoporderService.getCommonOrder(receiveTest.getOrderNo());
        WeixinMsgPushUtil.sendT10(commonOrder);
        logger.info("===上传检测报告完成，向用户推送门店收货T10模板消息结束=====");
        
        return  returnUrl + receiveTest.getOrderNo();
    }

    @RequestMapping(value = "/editReceiveTest/{orderno}/{type}" ,method = RequestMethod.GET)
    public String editReceive(@PathVariable("orderno")String orderno ,@PathVariable("type")String type ,Model model){
        HashMap<String , Object>  receiveTest =  receiveTestService.getByOrderno(orderno);
        model.addAttribute("receiveTest" , receiveTest);
        model.addAttribute("orderno" , orderno);
        model.addAttribute("type" , type);
        return "order/editReceiveTest";
    }

    /**
     * 更新收货证明
     * @param
     * @return
     */
    @RequestMapping(value = "/updateReceiveTest" )
    public String updateReceiveTest(ReceiveTest receiveTest , String type) throws IOException {
        if(receiveTest.getImgurl()!=null && receiveTest.getImgurl().indexOf("http://")==-1){
            //本地文件路径
            String path = receiveTest.getImgurl().replace("\"","");
            String key_suff = "receiveTest";
            //拼接上传的key
            String goodKey = key_suff  + "/"+path.substring(path.lastIndexOf("/")+1);
            //去七牛上传指定的文件并为其命名key
            QiniuUtil.upload(path , goodKey);
            //获得七牛图片外链
            String qiniuUrl = QiniuParamter.URL + goodKey;
            //删除本地文件
            TmFileUtil.delete(new File(path));
            receiveTest.setImgurl(qiniuUrl);
        }
        
        receiveTestService.update(receiveTest);
        String returnUrl = "";
        if("001".equals(type)){
            returnUrl =  "redirect:refurbish/detail/";
        }
        if("002".equals(type)){
            returnUrl =  "redirect:repair/detail/";
        }
        if("003".equals(type)){
            returnUrl =  "redirect:testing/detail/";
        }
        if("004".equals(type)){
            returnUrl =  "redirect:recycle/detail/";
        }
        if("005".equals(type)){
            returnUrl =  "redirect:exchange/detail/";
        }
        return returnUrl + receiveTest.getOrderNo();
    }



    /**
     * 更新订单状态
     */
    @ResponseBody
    @RequestMapping("/updateOrder")
    public int updateOrder(Shoporder shoporder){
        int n = shoporderService.update(shoporder);
        return n;
    }

    /**
     * 跳转到新增检测报告页面
     */
    @RequestMapping("/addCheckport/{orderno}/{type}/{serviceId}/{getway}")
    public String addCheckport(@PathVariable("orderno") String orderno , @PathVariable("type")String type , @PathVariable("serviceId")Integer serviceId , @PathVariable("getway")String getway , Model model){
        //根据订单好查询的到serviceid
        //更新service 保存检测报告字段
        //更新订单状态的为 待翻新(已检测)
        //返回原来的订单详情页面
        model.addAttribute("orderno" , orderno);
        model.addAttribute("serviceId" , serviceId);
        model.addAttribute("type" , type);
        model.addAttribute("getway" , getway);
        return "order/addCheckport";
//		int n = shoporderService.update(shoporder);
    }







    /**
     * 跳转到编辑检测报告页面
     */
    @RequestMapping("/editCheckport/{orderno}/{type}/{serviceId}")
    public String editCheckport(@PathVariable("orderno") String orderno , @PathVariable("type")String type ,@PathVariable("serviceId")Integer serviceId ,Model model){
        HashMap<String, Object>  checkReport = shoporderService.getReportByOrderno(orderno);
        model.addAttribute("checkReport" , checkReport);
        List<HashMap<String, Object>> pictures = shoporderService.getAllcheckpictures(serviceId);
        model.addAttribute("orderno" , orderno);
        model.addAttribute("serviceId" , serviceId);
        model.addAttribute("type" , type);
        model.addAttribute("pictures" , pictures);
        return "order/editCheckport";
    }
    /**
     * 更新检测报告
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateCheckport" )
    public String updateCheckport(Service service , String type, @RequestParam(value = "delIds[]")int[] delIds,  @RequestParam(value = "addImgs[]")String[] addImgs) throws IOException {
        shoporderService.updateCheckport(service, delIds, addImgs);
        return "ok";
    }


    /**
     * 跳转到检测报告页面
     */
    @RequestMapping("/saveCheckport")
    public String saveCheckport(String orderNo ,String type ,String checkreport ,String checkreportUrl[],Integer serviceId,String getway, Model model) throws IOException {
        //根据订单好查询的到serviceid
        //更新service 保存检测报告字段
        //更新订单状态的为 待翻新(已检测)
        //返回原来的订单详情页面
        shoporderService.saveCheckport(orderNo,type,checkreport,checkreportUrl,serviceId,getway);
        //保存详情轮播图

        String returnUrl = "";
        if("001".equals(type)){
            returnUrl =  "redirect:refurbish/detail";
        }
        if("002".equals(type)){
            returnUrl =  "redirect:repair/detail";
        }
        if("003".equals(type)){
            returnUrl =  "redirect:testing/detail";
        }
        if("004".equals(type)){
            returnUrl =  "redirect:recycle/detail";
        }
        if("005".equals(type)){
            returnUrl =  "redirect:exchange/detail";
        }
        if("006".equals(type)){
            returnUrl =  "redirect:shop/detail";
        }
        
        if("001".equals(type) || "002".equals(type) || "003".equals(type)){
			 logger.info("===上传检测报告完成，向用户推送T3模板消息开始=====");
		     CommonOrder commonOrder = shoporderService.getCommonOrder(orderNo);
		     WeixinMsgPushUtil.sendT3(commonOrder);
		     if("003".equals(type) && "002".equals(commonOrder.getGetWay())){
		    	 logger.info("==={}检测订单上传检测报告完成，用户选择上门取货，发送取货T9通知开始=====");
		    	 WeixinMsgPushUtil.sendT9(commonOrder);
		    	 logger.info("==={}检测订单上传检测报告完成，用户选择上门取货，发送取货T9通知结束=====");
		     }
		     logger.info("===上传检测报告完成，向用户推送T3模板消息结束=====");
        }
        
        return  returnUrl +"/" + orderNo;
    }

    /**
     * 确认服务 比如 确认是否翻新 是否维修 是否回收等 改变订单的状态
     */
    @ResponseBody
    @RequestMapping("/confirmService")
    public int  confirmService(String type,String orderno,String getway){
        String status = "";
        if("001".equals(type)){
            if("001".equals(getway)){
                status = "001006";   //待（平台）发货（已翻新）
            } else {
                status = "001007";   //待(客户)收货 不需要发货
            }
        }
        if("002".equals(type)){
            if("001".equals(getway)){
                status = "002008";   //待（平台发货）返回（已维修）
            } else {
                status = "002009";   //待(客户)收货 不需要发货
            }

        }
        int n = shoporderService.update(new Shoporder(orderno , status)) ;
        
        if(n == 1){
        	CommonOrder commonOrder = shoporderService.getCommonOrder(orderno);
        	if("002".equals(getway)){
        		commonOrder.setGetWay("002");
        		logger.info("======={}翻新/维修订单完成，发送到店取货T9通知开始=====",orderno);
        		WeixinMsgPushUtil.sendT9(commonOrder);
        		logger.info("======={}翻新/维修订单完成，发送到店取货T9通知结束=====",orderno);
        	}
        }
        
        return n;
    }


    /**
     * 客户自取确认服务 比
     */
    @ResponseBody
    @RequestMapping("/pickup")
    public int  pickup(String type,String orderno,String getway){
        String status = "";
        if("001".equals(type)){    //翻新
            status = "001008";   //待评价
        }
        if("002".equals(type)){  //维修
            status = "002010";   //待评价
        }
        if("003".equals(type)){    //翻新
            status = "003008";   //待评价
        }
        if("005".equals(type)){    //换款
            status = "005010";   //待评价
        }

        int n = shoporderService.update(new Shoporder(orderno , status)) ;
        
        return n;
    }


    /**
     * 商城退款申请通过
     */
    @ResponseBody
    @RequestMapping("/confirmRefund")
    public int  confirmRefund(String type,String orderno, String confirm){
        String status = "";
        if("006".equals(type)){
            if("001".equals(confirm)){
                status = "008";
            }else{
                status = "011";
            }
        }
        int n = shoporderService.update(new Shoporder(orderno , status)) ;
        return n;
    }


    /**
     * 拍照邮寄
     */
    @RequestMapping("/addOrderPicture/{orderno}/{type}/{openid}")
    public String addOrderPicture(@PathVariable("orderno")String orderno , @PathVariable("type") String type, @PathVariable("openid") String openid,Model model, HttpSession session){
        model.addAttribute("orderno" , orderno);
        model.addAttribute("type" , type);
        model.addAttribute("openid" , openid);
        if(session.getAttribute("express")==null){
            List<HashMap<String , Object>> express = shoporderService.findAllexpressCompanies();
            model.addAttribute("express" , express);
            session.setAttribute("express" , express);
        }else{
            model.addAttribute("express" , (List<HashMap<String , Object>>)session.getAttribute("express"));
        }
        return "order/addOrderPicture";
    }

    /**
     * 编辑平台发货物流信息 "logisticsnoComp" -> "YTO"
     */
    @RequestMapping("/editLogistinfo/{orderno}/{type}")
    public String editLogistinfo(@PathVariable("orderno")String orderno, @PathVariable("type") String type, Model model, HttpSession session){
        HashMap<String, Object> logists = shoporderService.getLogist(orderno);
        model.addAttribute("type" , type);
        model.addAttribute("orderno" , orderno);
        if(session.getAttribute("express")==null){
            List<HashMap<String , Object>> express = shoporderService.findAllexpressCompanies();
            model.addAttribute("express" , express);
            session.setAttribute("express" , express);
        }else{
            model.addAttribute("express" , (List<HashMap<String , Object>>)session.getAttribute("express"));
        }
        model.addAttribute("order",logists);
        return "order/editLogistinfo";
    }




    /**
     * 保存拍照邮寄信息
     */
    @RequestMapping("/saveOrderPicture")
    public String saveOrderPicture(Shoporder shoporder , String[] imgurl ,String openid) throws IOException {
    	//因为step2会更改订单状态，所以先在这里组装订单
    	CommonOrder commonOrder = shoporderService.getCommonOrder(shoporder.getOrderno());
    	//step2
        shoporderService.saveOrderPicture(shoporder , imgurl);
        String returnUrl = "";
        if("001".equals(shoporder.getType())){
            returnUrl =  "redirect:refurbish/detail";
        }
        if("002".equals(shoporder.getType())){
            returnUrl =  "redirect:repair/detail";
        }
        if("003".equals(shoporder.getType())){
            returnUrl =  "redirect:testing/detail";
        }
        if("004".equals(shoporder.getType())){
            returnUrl =  "redirect:recycle/detail";
        }
        if("005".equals(shoporder.getType())){
            returnUrl =  "redirect:exchange/detail";
        }
        if("006".equals(shoporder.getType())){
            returnUrl =  "redirect:shoporder/detail";
        }
        String  logisticCompany =   shoporderService.getlogisticCompany(shoporder.getLogisticsnocomp());
        //SendOrderPaySuccessMsg.sendGoodNotice(openid ,shoporder.getOrderno(),shoporder.getType(),logisticCompany ,shoporder.getLogisticsno());
        if("001".equals(shoporder.getType()) || "002".equals(shoporder.getType()) || "003".equals(shoporder.getType())){
        	if("001".equals(commonOrder.getGetWay())){
        		WeixinMsgPushUtil.sendT6(commonOrder);
        	}
        }
        
        if("004".equals(shoporder.getType())){
        	System.out.println("========放弃回收，拍照发货========");
        	System.out.println("订单状态："+commonOrder.getOrderStatus());
        	//if("004009".equals(commonOrder.getOrderStatus())){//放弃回收
        		commonOrder.setCustomerConfirm(false);
        		if("001".equals(commonOrder.getGetWay())){
            		WeixinMsgPushUtil.sendT8(commonOrder);
            	}else if("002".equals(commonOrder.getGetWay())){
            		WeixinMsgPushUtil.sendT5(commonOrder);
            	}
        	//}
        }
        
        if("005".equals(shoporder.getType())){//换款
        	System.out.println("=========放弃换款,拍照发货==========");
        	System.out.println("订单状态："+commonOrder.getOrderStatus());
        	if("005014".equals(commonOrder.getOrderStatus())){//放弃换款
        		commonOrder.setCustomerConfirm(false);
        		if("001".equals(commonOrder.getGetWay())){
            		WeixinMsgPushUtil.sendT8(commonOrder);
            	}else if("002".equals(commonOrder.getGetWay())){
            		WeixinMsgPushUtil.sendT5(commonOrder);
            	}
        	}else{
        		commonOrder.setCustomerConfirm(true);//确认换款
        		if("001".equals(commonOrder.getGetWay())){
            		WeixinMsgPushUtil.sendT8(commonOrder);
            	}
        	}
        }
        
        return  returnUrl +"/" + shoporder.getOrderno();
    }

    /**
     * 确认订单完成
     */
    @ResponseBody
    @RequestMapping("/confirmOK")
    public int  confirmOK(Shoporder shoporder){
        String status = "";
        if("001".equals(shoporder.getType())){
            status =  "001008";
        }
        if("002".equals(shoporder.getType())){
            status =  "002009";
        }
        if("003".equals(shoporder.getType())){
            status =  "003008";
        }
        if("004".equals(shoporder.getType())){
            status =  "004007";
        }
        if("005".equals(shoporder.getType())){
            status =  "001008";
        }
        if("006".equals(shoporder.getType())){
            status =  "004";  //待评价
        }
        shoporder.setShoporderstatuscode(status);
        int n = shoporderService.update(shoporder);
        return n;
    }

    /**
     * 根据快递单号 和 快递公司编码  查询物流信息
     * @param order
     * @return
     */
    @ResponseBody
    @RequestMapping("/getOrderTracesByJson")
    public HashMap<String , Object>   getOrderTracesByJson(Shoporder order) throws Exception {
        HashMap<String , Object> map = new HashMap<>();
        //查询买家发货物流信息
        if(TmStringUtils.isNotEmpty(order.getUserlogisticsno()) && TmStringUtils.isNotEmpty(order.getUserlogisticsnocomp())){
            JSONObject result = KdniaoTrackQueryAPI.getOrderTracesByJson((String)order.getUserlogisticsnocomp() , (String)order.getUserlogisticsno());
            map.put("userLogics" ,result);
        }
        //查询平台发货物流信息
        if(TmStringUtils.isNotEmpty(order.getLogisticsno()) && TmStringUtils.isNotEmpty(order.getLogisticsnocomp())){
            JSONObject result2 = KdniaoTrackQueryAPI.getOrderTracesByJson((String)order.getLogisticsnocomp() , (String)order.getLogisticsno());
            map.put("logics" ,result2);
        }
        return map;
    }

    /**
     * 定价  维修 和 回收
     */
    @ResponseBody
    @RequestMapping("/fixPrice")
    public String fixPrice(String orderno ,String type ,Double aturalprice, String openid){
        shoporderService.updateFixPrice(orderno , type , aturalprice ,openid);
        if("002".equals(type)){//维修
        	logger.info("=========维修订单定价后发送维修定价T11模板消息开始==========");
        	CommonOrder commonOrder = shoporderService.getCommonOrder(orderno);
        	WeixinMsgPushUtil.sendT11(commonOrder);
        	logger.info("=========维修订单定价后发送维修定价T11模板消息结束==========");
        }
        if("004".equals(type) || "005".equals(type)){
        	System.out.println("===回收/定价完成，向用户推送T3模板消息开始=====");
        	logger.info("===回收/定价完成，向用户推送T3模板消息开始=====");
		    CommonOrder commonOrder = shoporderService.getCommonOrder(orderno);
		    WeixinMsgPushUtil.sendT3(commonOrder);
		    logger.info("===回收/定价完成，向用户推送T3模板消息结束=====");
		    System.out.println("===回收/定价完成，向用户推送T3模板消息结束=====");
        }
        return "success";
    }

    /**
     * 回收金额确认
     */
    @ResponseBody
    @RequestMapping("/confirmRecycleMoney")
    public String confirmRecycleMoney(Shoporder shoporder, HttpServletRequest request){
        String backUsername = (String) request.getSession().getAttribute(SESSION_USER_USERNAME);
        shoporderService.updateConfirmRecycleMoney(shoporder, backUsername);
        return "success";
    }

    /**
     * 退款金额确认
     */
    @ResponseBody
    @RequestMapping("/confirmRefundMoney")
    public String confirmRefundMoney(Shoporder shoporder, HttpServletRequest request){
        String backUsername = (String) request.getSession().getAttribute(SESSION_USER_USERNAME);
        shoporderService.updateConfirmRecycleMoney(shoporder, backUsername);
        return "success";
    }


}
